package com.cmit.lee.myaop.factory;

import com.cmit.lee.myaop.invocation.ProxyMethodInvocation;
import com.cmit.lee.myaop.util.ClassUtils;
import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * <br/>
 *
 * @author liyuanchang
 * @version V1.0
 * @email liyuanchang@chinamobile.com
 * @date 2020-04-15 21:09
 */
public class ProxyFactory implements InvocationHandler {
    // 被代理的对象
    private Object target;
    // 被代理对象的所有拦截器
    List<MethodInterceptor> interceptorList = new ArrayList<>();

    public ProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxy() {
        Class<?>[] allInterfaces = ClassUtils.getAllInterfaces(target);
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), allInterfaces, this);
    }

    public void addInterceptor(MethodInterceptor interceptor) {
        interceptorList.add(interceptor);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        ProxyMethodInvocation invocation = new ProxyMethodInvocation(method, args, target, interceptorList);
        return invocation.proceed();
    }
}
